package com.myzuku.getmylocation.pro;

//TODO: Add a border around the image
//TODO: Add about location
//TODO: Create a better content provider. Don't use the media store.
//TODO: Address may be over 140 characters long.

import java.util.ArrayList;
import java.util.Date;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Bitmap.Config;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Projection;

public class LocateMeApp extends MapActivity {

	private MapController mapController;
	private MapView mapView;
	private TextView txtInfoPanel;
	private Button btnZoomIn;
	private Button btnZoomOut;
	private ImageButton btnFlipToSendMessage;
	private LinearLayout progressbarContainer;
	private ImageButton btnRefresh;
	private ViewGroup container;
	private ViewGroup layoutSendMessage;
	private ViewGroup layoutMapView;
	private MyLocationOverlay myLocationOverlay;
	private Button btnSendAddress;
	private Button btnSendUrl;
	private ImageView imgviewMap;

	static final private String TAG = "LocateMe";
	static final private String SCREEN_TAP_LOCATION_PROVIDER = "SCREEN_TAP";
	static final private int DIALOG_ENABLE_GPS = 1;
	static final private int DIALOG_PURCHASE_PRO_VERSION = 2;
	static final private int TOTAL_GPS_WAIT_TIME = 30000;
	static final private int GPS_STATUS_CHECK_INTERVAL = 2000;
	// private static final String MAP_IMAGE_FILE_NAME = "mapimage.jpg";
	// private static final String MAP_IMAGE_PATH_NAME = "LocateMe";
	private static final boolean IS_FREE_VERSION = false;
	private Location currentLocation = null;
	private String currentAddress = "";
	private Uri mapUri;
	private Timer refreshTimer;
	/**
	 * Save the URIs of the map images inserted in the media store. When the app
	 * is destroyed, all the map images will be deleted.
	 */
	private ArrayList<Uri> imageUris;

	private final class CustomMyLocationOverlay extends MyLocationOverlay {

		private Bitmap tapIcon;
		private GeoPoint tapLocationGeoPoint;

		private Boolean bugged = false;
		private Paint accuracyPaint;
		private Point center;
		private Point left;
		private Drawable drawable;
		private int width;
		private int height;

		@Override
		public synchronized boolean draw(Canvas canvas, MapView mapView,
				boolean shadow, long when) {

			super.draw(canvas, mapView, shadow, when);
			if (tapLocationGeoPoint != null) {
				Point screenPixelLocation = new Point();
				mapView.getProjection().toPixels(tapLocationGeoPoint,
						screenPixelLocation);

				canvas.drawBitmap(tapIcon, screenPixelLocation.x
						- tapIcon.getWidth() / 2, screenPixelLocation.y
						- tapIcon.getHeight(), null);
			}

			return false;
		}

		@Override
		protected void drawMyLocation(Canvas canvas, MapView mapView,
				Location lastFix, GeoPoint myLoc, long when) {
			if (!bugged) {
				try {
					super.drawMyLocation(canvas, mapView, lastFix, myLoc, when);
				} catch (Exception e) {
					bugged = true;
				}
			}

			if (bugged) {
				if (drawable == null) {
					accuracyPaint = new Paint();
					accuracyPaint.setAntiAlias(true);
					accuracyPaint.setStrokeWidth(2.0f);

					drawable = mapView.getContext().getResources().getDrawable(
							R.drawable.location_icon);
					width = drawable.getIntrinsicWidth();
					height = drawable.getIntrinsicHeight();
					center = new Point();
					left = new Point();
				}
				Projection projection = mapView.getProjection();

				double latitude = lastFix.getLatitude();
				double longitude = lastFix.getLongitude();
				float accuracy = lastFix.getAccuracy();

				float[] result = new float[1];

				Location.distanceBetween(latitude, longitude, latitude,
						longitude + 1, result);
				float longitudeLineDistance = result[0];

				GeoPoint leftGeo = new GeoPoint(
						(int) (latitude * 1e6),
						(int) ((longitude - accuracy / longitudeLineDistance) * 1e6));
				projection.toPixels(leftGeo, left);
				projection.toPixels(myLoc, center);
				int radius = center.x - left.x;

				accuracyPaint.setColor(0xff6666ff);
				accuracyPaint.setStyle(Style.STROKE);
				canvas.drawCircle(center.x, center.y, radius, accuracyPaint);

				accuracyPaint.setColor(0x186666ff);
				accuracyPaint.setStyle(Style.FILL);
				canvas.drawCircle(center.x, center.y, radius, accuracyPaint);

				drawable.setBounds(center.x - width / 2, center.y - height / 2,
						center.x + width / 2, center.y + height / 2);
				drawable.draw(canvas);
			}
		}

		@Override
		public boolean onTap(GeoPoint p, MapView map) {
			super.onTap(p, map);

			tapLocationGeoPoint = p;
			Location tapLocation = new Location(
					LocateMeApp.SCREEN_TAP_LOCATION_PROVIDER);
			tapLocation.setLatitude(p.getLatitudeE6() / 1e6);
			tapLocation.setLongitude(p.getLongitudeE6() / 1e6);
			tapLocation.setTime(new Date().getTime());
			LocateMeApp.this.centerMapAt(tapLocation);
			mapView.invalidate();

			updateAddressInfoPanel(tapLocation);

			return true;
		}

		public CustomMyLocationOverlay(Context context, MapView mapView) {
			super(context, mapView);

			tapIcon = BitmapFactory.decodeResource(mapView.getResources(),
					R.drawable.icon_red);
		}

	}

	private final class ButtonsClickListener implements OnClickListener {
		private boolean hitZoominLimit;
		private boolean hitZoomoutLimit;

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_zoom_in:
				if (hitZoomoutLimit) {
					hitZoomoutLimit = false;
					btnZoomOut.setEnabled(true);
				}
				hitZoominLimit = !mapController.zoomIn();
				if (hitZoominLimit) {
					btnZoomIn.setEnabled(false);
				}
				break;
			case R.id.btn_zoom_out:
				if (hitZoominLimit) {
					hitZoominLimit = false;
					btnZoomIn.setEnabled(true);
				}
				hitZoomoutLimit = !mapController.zoomOut();
				if (hitZoomoutLimit) {
					btnZoomOut.setEnabled(false);
				}
				break;

			case R.id.btn_refresh_gps:
				myLocationOverlay.disableMyLocation();
				myLocationOverlay.enableMyLocation();
				setProgressBarIndeterminateVisibility(true);
				txtInfoPanel.setVisibility(View.GONE);
				progressbarContainer.setVisibility(View.VISIBLE);
				btnFlipToSendMessage.setVisibility(View.INVISIBLE);

				btnRefresh.setEnabled(false);
				btnFlipToSendMessage.setEnabled(false);
				refreshGpsLocation();

				break;
			case R.id.btn_flip_to_send_message:
				LocateMeApp.this.setProgressBarIndeterminateVisibility(false);
				btnRefresh.setEnabled(true);
				refreshTimer.isCanceled = true;
				setMapImage();
				flipToSendMessageView(currentLocation);
				break;
			case R.id.btn_send_address:
				sendMessage((String) btnSendAddress.getText());
				break;
			case R.id.btn_send_url:
				if (IS_FREE_VERSION)
					sendMessage(getString(R.string.purchase_pro_version_dialog_message));
				else
					sendMessage((String) btnSendUrl.getText());

				break;
			case R.id.image_map:
				sendMapImage();
				break;
			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.map_layout);

		init();
	}

	private void init() {
		container = (ViewGroup) findViewById(R.id.container);
		layoutSendMessage = (ViewGroup) findViewById(R.id.layout_send_message);
		layoutMapView = (ViewGroup) findViewById(R.id.layout_map_view);

		mapView = (MapView) findViewById(R.id.mapview_new);
		mapController = mapView.getController();

		btnZoomIn = (Button) findViewById(R.id.btn_zoom_in);
		btnZoomOut = (Button) findViewById(R.id.btn_zoom_out);
		btnFlipToSendMessage = (ImageButton) findViewById(R.id.btn_flip_to_send_message);
		btnFlipToSendMessage.setEnabled(false);
		btnSendAddress = (Button) findViewById(R.id.btn_send_address);
		btnSendUrl = (Button) findViewById(R.id.btn_send_url);
		imgviewMap = (ImageView) findViewById(R.id.image_map);

		btnRefresh = (ImageButton) findViewById(R.id.btn_refresh_gps);
		btnRefresh.setEnabled(false);

		ButtonsClickListener buttonsClickListener = new ButtonsClickListener();
		btnZoomIn.setOnClickListener(buttonsClickListener);
		btnZoomOut.setOnClickListener(buttonsClickListener);
		btnFlipToSendMessage.setOnClickListener(buttonsClickListener);
		btnRefresh.setOnClickListener(buttonsClickListener);
		btnSendAddress.setOnClickListener(buttonsClickListener);
		btnSendUrl.setOnClickListener(buttonsClickListener);
		imgviewMap.setOnClickListener(buttonsClickListener);

		txtInfoPanel = (TextView) findViewById(R.id.txtview_panel_desc);
		txtInfoPanel.setVisibility(View.GONE);

		progressbarContainer = (LinearLayout) findViewById(R.id.progressbar_container);

		myLocationOverlay = new CustomMyLocationOverlay(this, mapView);
		mapView.getOverlays().add(myLocationOverlay);

		imageUris = new ArrayList<Uri>();

		setProgressBarIndeterminateVisibility(true);
		checkGpsEnabled();
		myLocationOverlay.enableMyLocation();
		refreshGpsLocation();

		// container
		// .setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_ENABLE_GPS:
			return new AlertDialog.Builder(LocateMeApp.this).setIcon(
					R.drawable.alert_dialog_icon).setTitle(
					R.string.enable_gps_dialog_title).setMessage(
					R.string.enable_gps_dialog_message).setPositiveButton(
					R.string.ok_button_value,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(Intent.ACTION_MAIN);
							intent.setClassName("com.android.settings",
									"com.android.settings.SecuritySettings");
							startActivity(intent);
						}
					}).create();
		case DIALOG_PURCHASE_PRO_VERSION:
			return new AlertDialog.Builder(this).setIcon(
					R.drawable.alert_dialog_icon).setTitle(
					R.string.purchase_pro_version_dialog_title).setMessage(
					R.string.purchase_pro_version_dialog_message)
					.setPositiveButton(R.string.ok_button_value,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
								}
							}).setNeutralButton(
							R.string.go_to_market_button_value,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Intent intent = new Intent(
											Intent.ACTION_VIEW);
									intent
											.setClassName(
													"com.android.vending",
													"com.android.vending.AssetBrowserActivity");
									startActivity(intent);
								}
							}).create();

		default:
			break;
		}
		return null;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (layoutSendMessage.getVisibility() == View.VISIBLE
				&& keyCode == KeyEvent.KEYCODE_BACK) {
			applyRotation(-1, 0, -90);
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	private void checkGpsEnabled() {
		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
				|| !locationManager
						.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
			showDialog(DIALOG_ENABLE_GPS);

		}
	}

	private void centerMapAt(Location loc) {

		int latE6 = (int) (loc.getLatitude() * 1e6);
		int lngE6 = (int) (loc.getLongitude() * 1e6);

		GeoPoint geoPoint = new GeoPoint(latE6, lngE6);
		mapController.animateTo(geoPoint);
	}

	private void refreshGpsLocation() {

		refreshTimer = new Timer(TOTAL_GPS_WAIT_TIME, GPS_STATUS_CHECK_INTERVAL);
		refreshTimer.start();

	}

	private final class Timer extends CountDownTimer {
		private boolean firstNetworkLocation = true;
		private boolean isCanceled = false;

		private Timer(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onTick(long millisUntilFinished) {
			// CountDownTimer.cancel() doesn't seem to work
			if (isCanceled)
				return;

			Location loc = myLocationOverlay.getLastFix();

			if (loc == null) {
				// Log.i(TAG, "NULL location in the first minute.");
				return;
			} else if (firstNetworkLocation
					&& loc.getProvider().equalsIgnoreCase(
							LocationManager.NETWORK_PROVIDER)) {
				Log.i(TAG, "Network location in the first minute.");
				mapController.setZoom(16);
				centerMapAt(loc);
				firstNetworkLocation = false;
			} else if (loc.getProvider().equalsIgnoreCase(
					LocationManager.GPS_PROVIDER)) {
				//Log.i(TAG, "GPS location in the first minute.");
				mapController.setZoom(16);
				centerMapAt(loc);
				setProgressBarIndeterminateVisibility(false);
				updateAddressInfoPanel(loc);
				btnRefresh.setEnabled(true);

				isCanceled = true;
				// cancel();
			}
		}

		@Override
		public void onFinish() {
			if (isCanceled)
				return;

			setProgressBarIndeterminateVisibility(false);
			Location loc = myLocationOverlay.getLastFix();
			updateAddressInfoPanel(loc);
			btnRefresh.setEnabled(true);

		}

	}

	private void updateAddressInfoPanel(Location loc) {
		txtInfoPanel.invalidate();
		btnFlipToSendMessage.invalidate();
		currentLocation = loc;
		currentAddress = "";

		boolean isLocated = false;

		String infoPanelText = "";
		if (loc == null) {
			infoPanelText = "Location is unavailable now. "
					+ "Please make sure you are outdoor and have a clear "
					+ "view of sky. You can tap on the map to pinpoint your location.";
		} else {
			int latE6 = (int) (loc.getLatitude() * 1e6);
			int lngE6 = (int) (loc.getLongitude() * 1e6);
			GeoPoint geoPoint = new GeoPoint(latE6, lngE6);

			ReverseGeocodingResult geocodingResult = ReverseGeocodingHelper
					.getGeocodingResult(geoPoint);

			if (geocodingResult.getAddress() != null) {
				String addressText = geocodingResult.getAddress() + "\n";

				if (loc.getProvider().equalsIgnoreCase(
						LocationManager.GPS_PROVIDER)) {
					infoPanelText = "Address from GPS:\n" + addressText;
					// btnFlipToSendMessage.setEnabled(true);
					currentAddress = addressText;
					isLocated = true;
				} else if (loc.getProvider().equalsIgnoreCase(
						LocationManager.NETWORK_PROVIDER)) {
					infoPanelText += "GPS is unavailable. Your network indicates your location "
							+ "is within the circle. You may tap the map to pinpoint your location.";
				} else if (loc.getProvider().equalsIgnoreCase(
						LocateMeApp.SCREEN_TAP_LOCATION_PROVIDER)) {
					infoPanelText = "Address from Screen Tap:\n" + addressText;
					currentAddress = addressText;
					isLocated = true;
				}

			} else {
				infoPanelText = "Unable to get the address from GPS or your screen tap. Please try again.";
			}
		}

		progressbarContainer.setVisibility(View.GONE);
		txtInfoPanel.setText(infoPanelText);
		txtInfoPanel.setVisibility(View.VISIBLE);

		displayAddressInAnimation();

		if (isLocated) {
			btnFlipToSendMessage.setEnabled(true);
			btnFlipToSendMessage.setVisibility(View.VISIBLE);
			displayFlipButtonInAnimation();
		} else {
			btnFlipToSendMessage.setEnabled(false);
			btnFlipToSendMessage.setVisibility(View.INVISIBLE);
		}
	}

	private void displayAddressInAnimation() {
		final View infoPanelParent = (View) txtInfoPanel.getParent();
		Animation animAddressText = new TranslateAnimation(-(infoPanelParent
				.getWidth()), infoPanelParent.getPaddingLeft(), 0, 0);
		animAddressText.setDuration(1250);
		animAddressText.setInterpolator(AnimationUtils.loadInterpolator(this,
				android.R.anim.decelerate_interpolator));
		txtInfoPanel.startAnimation(animAddressText);

	}

	private void displayFlipButtonInAnimation() {
		Animation animSendMessageButton = new TranslateAnimation(
				Animation.RELATIVE_TO_SELF, 1, Animation.RELATIVE_TO_SELF, 0,
				Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0);
		animSendMessageButton.setDuration(500);
		animSendMessageButton.setStartOffset(1250);
		animSendMessageButton.setInterpolator(AnimationUtils.loadInterpolator(
				this, android.R.anim.decelerate_interpolator));
		btnFlipToSendMessage.startAnimation(animSendMessageButton);
	}

	private void sendMessage(String content) {
		Intent sendSMSIntent = new Intent(Intent.ACTION_SEND);
		sendSMSIntent.putExtra(Intent.EXTRA_SUBJECT,
				getString(R.string.message_title));
		// sendSMSIntent.putExtra("sms_body", content);
		sendSMSIntent.putExtra(Intent.EXTRA_TEXT, content);
		// sendSMSIntent.setType("vnd.android-dir/mms-sms");
		sendSMSIntent.setType("text/plain");
		startActivity(sendSMSIntent);
	}

	private void setMapImage() {

		Bitmap mapImage = Bitmap.createBitmap(mapView.getWidth(), mapView
				.getHeight(), Config.RGB_565);
		mapView.draw(new Canvas(mapImage));
		imgviewMap.setImageBitmap(mapImage);

		String currentUrl = null;
		if (IS_FREE_VERSION) {
			Bitmap freeVersionMap = BitmapFactory.decodeResource(
					getResources(), R.drawable.map);

			currentUrl = Images.Media.insertImage(getContentResolver(),
					freeVersionMap, "Meet Here Sample Map Image", "");

			// If a sample image was inserted to the media gallery before,
			// just delete the old ones. Otherwise it's annoying to the user.
			String urlPathSegment = currentUrl.substring(0, currentUrl.lastIndexOf("/"));
			Cursor cursor = Images.Media.query(getContentResolver(), Uri
					.parse(urlPathSegment), null,
					"title = \"Meet Here Sample Map Image\"", null, null);
			if (cursor.getCount() > 1) {
				//Log.i(TAG, "Current url: " + currentUrl);

				cursor.moveToFirst();
				do {
					String id = cursor.getString(cursor.getColumnIndex("_id"));
					String oldUrl = urlPathSegment + "/" + id;
					if (!oldUrl.equals(currentUrl)) {
						getContentResolver().delete(Uri.parse(oldUrl), null, null);
					}
				} while (cursor.moveToNext());
			}

		} else {
			currentUrl = Images.Media.insertImage(this.getContentResolver(), mapImage,
					"Map Image", "Screenshot of map image");

		}

		// Log.i(TAG, Uri.parse(url).toString());
		//
		// String filePath = "";
		// try {
		// String dirPath = Environment.getExternalStorageDirectory()
		// .getCanonicalPath().toString()
		// + "/" + MAP_IMAGE_PATH_NAME;
		//
		// filePath += dirPath + "/" + MAP_IMAGE_FILE_NAME;
		//
		// File dirPathFile = new File(dirPath);
		//
		// if (!dirPathFile.exists()) {
		// if (!dirPathFile.mkdir()) {
		// Log.e(TAG, "Can't create dir in sd card.");
		// return;
		// }
		// }
		//
		// // Log.i(TAG, "File path: " + filePath);
		// FileOutputStream fileoutputStream = new FileOutputStream(new File(
		// filePath));
		// mapImage.compress(CompressFormat.JPEG, 80, fileoutputStream);
		//
		// } catch (FileNotFoundException e) {
		// Log.e(TAG, "Can't save map image", e);
		// } catch (IOException e) {
		// Log.e(TAG, "Error in getting the external storage path", e);
		// }
		//
		// if (!filePath.equalsIgnoreCase("")) {
		// mapUri = Uri.parse("file://" + filePath);
		// }

		if (currentUrl != null) {
			mapUri = Uri.parse(currentUrl);
			imageUris.add(mapUri);
		} else {
			Toast toast = Toast.makeText(this,
					"No memory card found. Image cannot be sent.",
					Toast.LENGTH_LONG);
			toast.show();
			imgviewMap.setEnabled(false);
		}

	}

	private void sendMapImage() {
		Intent sendImageIntent = new Intent(Intent.ACTION_SEND);
		if (IS_FREE_VERSION) {
			sendImageIntent.putExtra(Intent.EXTRA_TEXT,
					getString(R.string.purchase_pro_version_dialog_message));
			sendImageIntent.putExtra("sms_body",
					getString(R.string.purchase_pro_version_dialog_message));
			sendImageIntent.putExtra(Intent.EXTRA_STREAM, mapUri);
		} else {
			sendImageIntent.putExtra("sms_body",
					getString(R.string.map_message_content));
			sendImageIntent.putExtra(Intent.EXTRA_TEXT,
					getString(R.string.map_message_content));
			sendImageIntent.putExtra(Intent.EXTRA_STREAM, mapUri);
		}

		sendImageIntent.putExtra(Intent.EXTRA_SUBJECT,
				getString(R.string.message_title));
		sendImageIntent.setType("image/png32");
		startActivity(sendImageIntent);

	}

	private String getLocationURL(Location loc) {
		if (loc == null)
			return "";

		double latitude = loc.getLatitude();
		double longitude = loc.getLongitude();

		return "http://maps.google.com/maps?q=loc:"
				+ String.format("%.6f", latitude) + "%2C"
				+ String.format("%.6f", longitude);

	}

	private void flipToSendMessageView(Location loc) {
		btnSendUrl.setText("My location:\n" + getLocationURL(loc));
		btnSendAddress.setText("At/near this address:\n" + currentAddress);

		applyRotation(1, 0, 90);
	}

	/**
	 * This method flip between the map view and message view.
	 * 
	 * @param direction
	 *            When larger than or equal to 1, it flips from the map view to
	 *            the message view. When less than 1, it flips from the message
	 *            view to the map view.
	 * @param fromAngle
	 *            Starting Angle
	 * @param toAngle
	 *            Ending Angle
	 */
	private void applyRotation(int direction, float fromAngle, float toAngle) {
		final float centerX = container.getWidth() / 2.0f;
		final float centerY = container.getHeight() / 2.0f;

		final Rotate3dAnimation rotation = new Rotate3dAnimation(fromAngle,
				toAngle, centerX, centerY, 310.0f, true);
		rotation.setDuration(500);
		rotation.setFillAfter(true);
		rotation.setInterpolator(new AccelerateInterpolator());
		rotation.setAnimationListener(new MyAnimationListener(direction));

		container.startAnimation(rotation);

	}

	private final class MyAnimationListener implements AnimationListener {
		private final int direction;

		private MyAnimationListener(int direction) {
			this.direction = direction;
		}

		@Override
		public void onAnimationStart(Animation animation) {
		}

		@Override
		public void onAnimationRepeat(Animation animation) {
		}

		@Override
		public void onAnimationEnd(Animation animation) {
			container.post(new SwapViews(direction));
		}
	}

	private final class SwapViews implements Runnable {
		private final int direction;

		private SwapViews(int direction) {
			this.direction = direction;
		}

		@Override
		public void run() {
			final float centerX = container.getWidth() / 2.0f;
			final float centerY = container.getHeight() / 2.0f;
			Rotate3dAnimation rotation;

			if (direction >= 1) {
				layoutMapView.setVisibility(View.GONE);
				layoutSendMessage.setVisibility(View.VISIBLE);
				rotation = new Rotate3dAnimation(-90, 0, centerX, centerY,
						310.0f, false);
			} else {
				layoutSendMessage.setVisibility(View.GONE);
				layoutMapView.setVisibility(View.VISIBLE);
				rotation = new Rotate3dAnimation(90, 0, centerX, centerY, 310f,
						false);
			}

			rotation.setDuration(500);
			rotation.setFillAfter(true);
			rotation.setInterpolator(new DecelerateInterpolator());

			container.startAnimation(rotation);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		myLocationOverlay.disableMyLocation();
	}

	@Override
	protected void onStop() {
		super.onStop();

	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	protected void onDestroy() {
		// for (Uri uri : imageUris) {
		// getContentResolver().delete(uri, null, null);
		// }

		super.onDestroy();
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

}
